package timing.ukulele.auth.security.handler;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import timing.ukulele.auth.authorization.JwtAuthorizationToken;
import timing.ukulele.auth.security.model.CustomGrantedAuthority;
import timing.ukulele.auth.security.user.BaseUserDetail;
import timing.ukulele.auth.support.RedisOperator;
import timing.ukulele.auth.util.JsonUtils;
import timing.ukulele.common.data.ResponseData;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static timing.ukulele.share.Constant.*;

@Slf4j
public class UkuleleLogoutSuccessHandler implements LogoutSuccessHandler {
    private final JwtDecoder jwtDecoder;
    private final RedisOperator<String> redisOperator;

    public UkuleleLogoutSuccessHandler(JwtDecoder jwtDecoder, RedisOperator<String> redisOperator) {
        this.jwtDecoder = jwtDecoder;
        this.redisOperator = redisOperator;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        // 删除缓存
        String authHeader = request.getHeader(AUTHORIZATION_HEADER);
        if (authHeader != null && authHeader.startsWith(TOKEN_PREFIX)) {
            String token = authHeader.substring(7);
            try {
                Jwt decode = jwtDecoder.decode(token);
                if (decode != null) {
                    redisOperator.delete(TOKEN_CACHE_PREFIX + decode.getClaimAsString("sub"));
                }
            } catch (Exception exception) {
                log.error(exception.getMessage());
            }
        }
        log.debug("登出成功.");
        ResponseData<String> success = ResponseData.success();
        success.setData("登出成功.");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(JsonUtils.objectCovertToJson(success));
        response.getWriter().flush();
    }
}
